<?php
/**
 * Created by PhpStorm.
 * User: cephei
 * Date: 12/7/15
 * Time: 8:21 PM
 */

namespace Plugins\Route;

class Plugin_Route{
    private $routePath=[];

    public function __construct()
    {
        $routeJson = file_get_contents(ROOT_PATH . "/Storage/Configs/route_path.json");
        $this->routePath = json_decode($routeJson);
    }

    public function __destruct()
    {
        // TODO: Implement __destruct() method.
        $routeJson = json_encode($this->routePath);
        file_put_contents(ROOT_PATH . "/Storage/Configs/route_path.json",$routeJson);
    }

    public function findWay($request){
        $requestMethod = $request["REQUEST_METHOD"];
        $queryString = $request["QUERY_STRING"];
        $requestUri = str_replace("?$queryString","",$request["REQUEST_URI"]);
        foreach($this->routePath as $route){
            $pattern = str_replace('/','\/',$route->url);
            if(strpos($pattern,'\?')===false)
                $match = preg_match_all('/'.$pattern.'/',$requestUri,$arr);
            else
                $match = preg_match_all('/'.$pattern.'/',"$requestUri?$queryString",$arr);
            if($match&&$requestMethod==$route->httpmethod){
                if(count($arr)>1){
                    $instance = new $route->class();
                    call_user_func_array([$instance,$route->method],array_column(array_splice($arr,1),0));
                }else{
                    $instance = new $route->class();
                    $method = $route->method;
                    $instance->$method();
                }
            }
        }
    }
    public function registerWay($way,$method,$point){
        $point = explode("@",$point);
        if(count($point)==2) {
            $routePath = new \stdClass();
            $routePath->url = $way;
            $routePath->class = $point[0];
            $routePath->method = $point[1];
            $routePath->httpmethod = $method;
            $this->routePath[] = $routePath;
        }
    }
    public function checkRoutePoint($way,$method){
        foreach($this->routePath as $route){
            if($route->url==$way&&$route->httpmethod==$method){
                return true;
            }
        }
        return false;
    }
}